package com.sap.mall.product.web;

import com.sap.mall.product.entity.CategoryEntity;
import com.sap.mall.product.service.CategoryService;
import com.sap.mall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        // 1、查出所有得一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Catogorys();
        //视图解析器进行拼串，
        //prefix = "classpath:/templates/";
        //suffix = ".html";
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        RLock lock = redisson.getLock("my-lock");
        lock.lock();

        lock.lock(10, TimeUnit.SECONDS);  // 10秒自动解锁，自动解锁时间一定要大于业务的执行时间
        try {
            System.out.println("加锁成功，执行业务。。" + Thread.currentThread().getId());
            Thread.sleep(20000);

        } catch (Exception e) {

        } finally {
            lock.unlock();
            System.out.println("解锁成功。。" + Thread.currentThread().getId());
        }

        return "";

    }


    // 保证一定能读到最新数据，修改期间，写锁是一个排他锁（互斥锁，独享所），读锁是一个共享锁
    // 写锁没释放，读就必须等待。
    // 读 + 读 ；相当于无锁 所有当前的读锁，他们都会同时枷锁成功
    // 写 + 读 :等待写完成
    // 写 + 写 :阻塞
    // 读 + 写 :有读锁，写需要等待
    // 只要有写的存在，必须等待
    @GetMapping("/write")
    @ResponseBody
    public String writevalue() {
        String s = UUID.randomUUID().toString();

        RReadWriteLock readWriteLock = redisson.getReadWriteLock("readWriteLock");
        RLock writeLock = readWriteLock.writeLock();
        try {
            writeLock.lock();
            System.out.println("写锁加锁成功。。。");
            Thread.sleep(20 * 1000);
            redisTemplate.opsForValue().set("uuid", s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
            System.out.println("写锁解锁成功。。。");
        }
        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readvalue() {

        String s = "";
        RReadWriteLock readWriteLock = redisson.getReadWriteLock("readWriteLock");
        RLock readLock = readWriteLock.readLock();
        try {
            readLock.lock();
            System.out.println("读锁加锁成功。。。");
            Thread.sleep(20 * 1000);
            s = redisTemplate.opsForValue().get("uuid");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
            System.out.println("读锁解锁成功。。。");
        }
        return s;
    }


    @GetMapping("/lockDoor")
    @ResponseBody
    public String coundDownLock() throws InterruptedException {
        RCountDownLatch countDownLatch = redisson.getCountDownLatch("door");

        countDownLatch.trySetCount(5);
        countDownLatch.await();

        return "放假了";
    }


    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogog(@PathVariable("id") Long id) throws InterruptedException {
        RCountDownLatch countDownLatch = redisson.getCountDownLatch("door");
        countDownLatch.countDown();

        return id + "班的人都走了";
    }

    /**
     * 限流
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {

        RSemaphore park = redisson.getSemaphore("park");
//        park.acquire();

        boolean b = park.tryAcquire();
        return "ok=>"+b;

    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();
        return "ok";
    }
}
